<?php

class AdminController extends AbstractAdminController
{
	public function actionList($categoryId = null)
	{
        $oGoods = new Goods();

        $oRowset = $oGoods->getAll($this->oPager, $categoryId);

		$this->render('list', array(
            'oRowset' => $oRowset,
		    'categoryId' => $categoryId
        ));
	}

    public function actionEditor($categoryId = null)
    {
	    $toView = array();

        $oGoods = new Goods();
        $oParser = new Parser();
        $oPhotos = new Photos();
        $oVideo = new Video();
        $oGoodsProperty = new GoodsProperty();

        $id = $this->_getParam('id');

        if($this->_isPost())
        {
            $attr = $this->_getPost();

	        $attr['user_id'] = $this->_userInfo->id;

            if($oGoods = $oGoods->saveRow($attr))
            {
                $oPhotos->saveByTarget($oGoods, $this->_getPost());
                $oVideo->saveByTarget($oGoods, $this->_getPost());
	            $oGoodsProperty->saveByTarget($oGoods, $this->_getParam('property_value'), $this->_getParam('property_size_id'));

//                if($this->_isXmlHttpRequest())
//                    Yii::app()->end();
//                else
                    return $this->redirect(Yii::app()->createUrl('/admin/goods/list'));
            }
        }

        if($this->_isXmlHttpRequest())
            Yii::app()->end();

	    if($id > 0)
	        $oGoodsRow = $oGoods->findByPk($id);

	    $oRow = $oGoodsRow;

	    $oCategories = new Categories();
	    $aCategoriesIds = $oCategories->getAllParents($oRow->category_id);
	    $aCategoriesIds[$oRow->category_id] = $oRow->category_id;
//		    print_r($aCategoriesIds); exit;

	    $oCategoryProperty = new CategoryProperty();
	    $oProperties = $oCategoryProperty->getByCategoryId($aCategoriesIds);

	    $aProperties = array();
	    foreach($oProperties as $oProperty)
		    $aProperties[$oProperty->id] = $oProperty;

	    if($aProperties)
	    {
		    $oPropertyValue = new PropertyValue();
		    $oValues = $oPropertyValue->findAllBySql("SELECT * FROM property_value WHERE property_id IN(". implode(', ', array_keys($aProperties)).")");

		    foreach($oValues as $oValue)
		    {
			    if(isset($aProperties[$oValue->property_id]))
			        $aProperties[$oValue->property_id]->values[] = $oValue;
		    }
	    }

	    $toView['oProperties'] = $aProperties;

	    $oGoodsProperty = new GoodsProperty();
	    $oGoodsProperties = $oGoodsProperty->findAllByAttributes(array('goods_id' => $oRow->id));

	    $aGoodsProperties = array();
	    foreach($oGoodsProperties as $oGProperty)
		    $aGoodsProperties[$oGProperty->value_id][$oGProperty->property_id] = $oGProperty->stock_value_id > 0 ? $oGProperty->stock_value_id : true;

	    $toView['aGoodsProperties'] = $aGoodsProperties;

	    if($oGoodsRow)
	    {
		    $oPhotos->selectAllByRow($oGoodsRow);
		    $oVideo->selectAllByRow($oGoodsRow);

		    $oGoods = new Goods();
		    $toView['oColorsRowset'] = $oGoods->getAllColors($oGoodsRow);
	    }

	    $oParsers = $oParser->findAll('enabled = 1');

	    $toView['oRow'] = $oGoodsRow;
	    $toView['oParsers'] = $oParsers;
	    $toView['categoryId'] = $categoryId;

        $this->render('edit', $toView);
    }

    public function actionDelete($id = null)
    {
        $oGoods = new Goods();
        $oPhoto = new Photos();
        $oFiles = new Files();

        $oGoods = $oGoods->findByPk($id);

        $oPhoto->selectByRow($oGoods);

        if(!empty($oGoods) && !empty($oGoods['photos']))
        {
            foreach($oGoods['photos'] as $oPhoto)
            {
                $oFiles->deleteDirectory(PUBLIC_PATH . $oPhoto->path);

                $oPhoto->delete();
            }
        }

        $oGoods->delete();

        $returnUrl = Yii::app()->user->returnUrl;

        if(!empty($_SERVER['HTTP_REFERER']))
            $returnUrl = $_SERVER['HTTP_REFERER'];

        return $this->redirect($returnUrl);
    }

	public function actionProperties($categoryId)
	{
		$toView = array();

		$oCategories = new Categories();
		$aCategoriesIds = $oCategories->getAllParents($categoryId);
		$aCategoriesIds[$categoryId] = $categoryId;
//		    print_r($aCategoriesIds); exit;

		$oCategoryProperty = new CategoryProperty();
		$oProperties = $oCategoryProperty->getByCategoryId($aCategoriesIds);

		$aProperties = array();
		foreach($oProperties as $oProperty)
			$aProperties[$oProperty->id] = $oProperty;

		if(count($aProperties))
		{
			$oPropertyValue = new PropertyValue();
			$oValues = $oPropertyValue->findAllBySql("SELECT * FROM property_value WHERE property_id IN(". implode(', ', array_keys($aProperties)).")");

			foreach($oValues as $oValue)
			{
				if(isset($aProperties[$oValue->property_id]))
					$aProperties[$oValue->property_id]->values[] = $oValue;
			}
		}

		$toView['oProperties'] = $aProperties;

		$this->layout = 'ajax';
		$this->render('properties', $toView);
	}

	public function actionParser()
	{
		if(!$this->_getParam('parser_id') || !$this->_getParam('url'))
			exit;

		$oParser = new Parser();
		$oParser = $oParser->findByPk($this->_getParam('parser_id'));

		if(!$oParser)
			exit;

		$oGrabber = new Grabber();
		$aPriceRow = $oGrabber->getRow($oParser->class, $this->_getParam('url'));

		echo json_encode($aPriceRow);
		exit;
	}

	public function actionStorePhotos($id)
	{
		if(!$id)
			exit;

		$oGoods = new Goods();
		$oStoreUrl = new StoreUrl();
		$oGoodsRow = $oGoods->id($id)->find();

		if(empty($oGoodsRow))
			exit;

		$url = $oGoodsRow->original_url;

		if(!$url)
			exit;

		$oUrlRow = $oStoreUrl->findByAttributes(array('url' => $url));
		if(empty($oUrlRow->data))
			exit;

		$aRow = json_decode($oUrlRow->data, true);

		if(!empty($aRow['photos']) && $oGoodsRow)
		{
			$i = 0;
			foreach($aRow['photos'] as $imgSrc)
			{
				$oPhoto = new Photos();
				$oPhoto = $oPhoto->findByAttributes(array('original_url' => $imgSrc));

				if($oPhoto && $oPhoto->id > 0)
					continue;

				$oThumb = new Thumbnail($imgSrc);
				$result = $oThumb->crop('/-/', Yii::app()->params->photos[$oGoodsRow->getTableName()], $oGoodsRow->alias, $oGoodsRow->getPrimaryKey());

				if($result)
				{
					$oPhoto = new Photos();
					$oPhoto->attributes = array(
						'target_type' => $oGoodsRow->getTableName(),
						'target_id' => $oGoodsRow->getPrimaryKey(),
						'path' => $result['dir'],
						'file' => $result['file'],
						'upload_user' => 1,
						'upload_time' => time(),
						'is_main' => ($i++ == 0 ? 1 : 0),
						'original_url' => $imgSrc
					);
					$oPhoto->save();

					$url = $result['dir'].$result['file'];
					echo '<a target="_blank" href="'. $url .'">'. $url .'</a><br />';
				}
			}

			echo json_encode(array('success' => true));
		}

		exit;
	}

	public function actionLoadframe($url)
	{
		Yii::import('application.components.grabber.Browser');

		$oBrowser = new Browser();
		$html = $oBrowser->get($url);

		echo $html; exit;
	}

}